<template>
  <div class="wishes-layout">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-content">
        <div class="logo">{{ isLoggedIn ? '生日愿望墙' : '生日祝福墙' }}</div>
        <div class="user-info" v-if="isLoggedIn">
          <span class="username">{{ userStore.currentUser?.userName }}</span>
          <a-button type="text" class="logout-btn" @click="handleLogout">
            退出登录
          </a-button>
        </div>
        <div class="user-info" v-else>
          <a-button type="text" class="login-btn" @click="$router.push('/login')">
            登录
          </a-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 发布愿望/祝福表单 -->
      <div class="wish-form-container">
        <a-card :bordered="false" class="wish-form-card">
          <a-textarea
            v-model:value="newWish"
            :rows="4"
            :placeholder="isLoggedIn ? '写下你的生日愿望...' : '写下你的祝福语...'"
            :disabled="loading"
            @keydown.ctrl.enter="handleSubmit"
            class="wish-input"
          />
          <div class="form-footer">
            <a-tag color="pink" class="tip-tag">
              <span class="tag-icon">💡</span>
              按 Ctrl + Enter 快速发布
            </a-tag>
            <a-button
              type="primary"
              :loading="loading"
              @click="handleSubmit"
              :disabled="!newWish.trim()"
              class="submit-btn"
            >
              {{ isLoggedIn ? '发布愿望' : '发布祝福' }}
            </a-button>
          </div>
        </a-card>
      </div>

      <!-- 愿望/祝福列表 -->
      <div class="wishes-container">
        <a-row :gutter="[24, 24]">
          <a-col
            v-for="wish in wishes"
            :key="wish.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <a-card
              :bordered="false"
              class="wish-card"
              :bodyStyle="{ padding: '20px' }"
            >
              <div class="wish-content">{{ wish.wishContent }}</div>
              <div class="wish-meta">
                <div class="wish-user">
                  <a-avatar :size="28">
                    {{ wish.userName?.[0] || '?' }}
                  </a-avatar>
                  <span class="user-name">{{ wish.userName || '匿名用户' }}</span>
                </div>
                <div class="wish-time">
                  {{ formatTime(wish.createTime) }}
                </div>
              </div>
              <div class="wish-actions" v-if="isLoggedIn && isOwner(wish)">
              
                <a-button
                  type="text"
                  danger
                  @click="handleDelete(wish)"
                  class="action-btn"
                >
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>

    <!-- 编辑愿望弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isLoggedIn ? '编辑愿望' : '编辑祝福'"
      @ok="editWish"
      @cancel="handleCancel"
      :ok-text="'提交'"
      :cancel-text="'取消'"
    >
      <a-form @submit.prevent="editWish">
        <a-form-item :label="isLoggedIn ? '编辑愿望' : '编辑祝福'">
          <a-input v-model="editedWish" required />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { wishesApi } from '../api/wishes'
import { userApi } from '../api/user'
import { message, Modal } from 'ant-design-vue'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 计算属性：判断是否登录
const isLoggedIn = computed(() => userStore.isLoggedIn)

const wishes = ref([])
const newWish = ref('')
const loading = ref(false)
const modalVisible = ref(false)
const editedWish = ref('')
const currentWish = ref(null)

// 获取愿望列表
const fetchWishes = async () => {
  try {
    const res = await wishesApi.getWishes()
    if (res.code === 0 && res.data) {
      wishes.value = res.data
      // message.success('获取列表成功')
    } else {
      message.error('请联系管理员~:' + (res.data?.message || '未知错误'))
    }
  } catch (error) {
    message.error('请联系管理员~:' + error.message)
  }
}

// 提交新愿望/祝福
const handleSubmit = async () => {
  if (loading.value) return

  if (!newWish.value.trim()) {
    message.warning(isLoggedIn.value ? '愿望内容不能为空' : '祝福内容不能为空')
    return
  }

  loading.value = true
  try {
    await wishesApi.createWish({ 
      wishContent: newWish.value,
      isAnonymous: !isLoggedIn.value // 未登录用户发布为匿名祝福
    })
    message.success('发布成功')
    newWish.value = ''
    await fetchWishes()
  } catch (error) {
    message.error(error.message || '发布失败')
  } finally {
    loading.value = false
  }
}

// 编辑和删除功能只对登录用户开放
const handleEdit = (wish) => {
  if (!isLoggedIn.value) return
  currentWish.value = wish
  editedWish.value = wish.wishContent
  modalVisible.value = true
}

const handleCancel = () => {
  modalVisible.value = false
  editedWish.value = ''
  currentWish.value = null
}

const editWish = async () => {
  if (!isLoggedIn.value || !currentWish.value) {
    message.error('没有权限或没有选中的内容')
    return
  }

  if (!editedWish.value.trim()) {
    message.warning(isLoggedIn.value ? '愿望内容不能为空' : '祝福内容不能为空')
    return
  }

  try {
    await wishesApi.updateWish({
      id: currentWish.value.id,
      wishContent: editedWish.value
    })
    message.success('编辑成功')
    modalVisible.value = false
    editedWish.value = ''
    currentWish.value = null
    await fetchWishes()
  } catch (error) {
    message.error('编辑失败: ' + (error.message || '未知错误'))
  }
}

const handleDelete = (wish) => {
  if (!isLoggedIn.value) return
  
  Modal.confirm({
    title: '确定要删除吗？',
    content: '删除后将无法恢复',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await wishesApi.deleteWish(wish.id)
        message.success('删除成功')
        await fetchWishes()
      } catch (error) {
        message.error('删除失败: ' + (error.message || '未知错误'))
      }
    }
  })
}

// 退出登录
const handleLogout = () => {
  Modal.confirm({
    title: '确定要退出登录吗？',
    async onOk() {
      try {
        await userApi.logout()
        userStore.clearUserState()
        await router.push('/login')
        message.success('已退出登录')
      } catch (error) {
        message.error('退出失败: ' + (error.message || '未知错误'))
      }
    }
  })
}

// 判断是否是内容所有者
const isOwner = (wish) => {
  return isLoggedIn.value && userStore.currentUser?.id === wish.userId
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchWishes()
})
</script>

<style scoped>
.wishes-layout {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  height: 64px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 20px;
  font-weight: 600;
  color: #ff6b81;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.username {
  font-size: 14px;
  color: #666;
}

.logout-btn {
  color: #ff6b81;
}

.logout-btn:hover {
  color: #ff5268;
  background: rgba(255, 107, 129, 0.1);
}

.main-content {
  max-width: 1200px;
  margin: 88px auto 32px;
  padding: 0 24px;
}

.wish-form-container {
  margin-bottom: 32px;
}

.wish-form-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.wish-input {
  border-radius: 8px;
  border: 1px solid #eee;
  padding: 12px;
  font-size: 14px;
  resize: none;
  transition: all 0.3s;
}

.wish-input:focus {
  border-color: #ff6b81;
  box-shadow: 0 0 0 2px rgba(255, 107, 129, 0.1);
}

.form-footer {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tip-tag {
  border: none;
  background: rgba(255, 107, 129, 0.1);
}

.tag-icon {
  margin-right: 4px;
}

.submit-btn {
  background: #ff6b81;
  border: none;
}

.submit-btn:hover {
  background: #ff5268;
}

.wish-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s;
}

.wish-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.wish-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 16px;
  min-height: 60px;
}

.wish-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.wish-user {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 13px;
  color: #666;
}

.wish-time {
  font-size: 12px;
  color: #999;
}

.wish-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.action-btn {
  font-size: 13px;
  padding: 4px 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content {
    padding: 0 16px;
    margin-top: 80px;
  }

  .header-content {
    padding: 0 16px;
  }

  .logo {
    font-size: 18px;
  }
}

@media (max-width: 576px) {
  .wish-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .wish-actions {
    justify-content: flex-start;
  }
}
</style>